package com.mediacloud.app.newsmodule.activity

import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.View
import android.widget.RelativeLayout
import com.mediacloud.app.model.activity.BaseBackActivity
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.utils.FileTypeJudge
import com.tencent.smtt.sdk.TbsReaderView
import kotlinx.android.synthetic.main.activity_file_read.*
import org.jetbrains.anko.toast
import java.io.BufferedInputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.net.HttpURLConnection
import java.net.MalformedURLException
import java.net.URL
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException

/**
 * 文件浏览页面
 * wy
 * */
class FileReadActivity : BaseBackActivity(), TbsReaderView.ReaderCallback {

    override fun getLayoutResID(): Int {
        return R.layout.activity_file_read
    }

    //远端地址
    private var fileUrl: String? = null

    //文件名
    var fileName: String? = null

    //本地文件地址
    var filePath: String? = null
    private var mTbsReaderView: TbsReaderView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        fileUrl = intent.getStringExtra("FILE_URL")
        fileName = intent.getStringExtra("FILE_NAME")
        filePath = intent.getStringExtra("FILE_PATH")

        try {
            mTbsReaderView = TbsReaderView(this, this)
        } catch (e: Exception) {
            e.printStackTrace()
            toast("浏览服务初始化失败")
            finish()
        }

        //先检测是不是本地的文件
        if (filePath != null) {
            val file = File(filePath)
            if (file.exists()) {
                openFile(file)
            }
        } else {
            //不是本地文件就走下载流程
            val fileDir = File(Environment.getExternalStorageDirectory(), "$packageName/file")
            if (!fileDir.exists()) {
                fileDir.mkdirs()
            }
            val md5Name = md5("$fileUrl") /*+ "." + parseFormat("$fileName")*/
            val file = File(fileDir, "$md5Name.$fileName")
            if (file.exists() && file.length() != 0L) {
                openFile(file)
            } else {
                if (file.exists()) {
                    file.delete()
                }
                download(fileUrl, file)
            }
        }
    }

    /**
     * 开始下载
     */
    private fun download(url: String?, file: File) {
        mLoadingView.visibility = View.VISIBLE
        Thread(Runnable {
            try {
                val fileOutput = FileOutputStream(file)
                var urlConnection: HttpURLConnection? = null
                val urlObj = URL(url)
                urlConnection = urlObj.openConnection() as HttpURLConnection
                var downloadedSize = 0
                var counter = 0
                val buffer = ByteArray(1024)
                var bufferLength = 0
                val inPut = BufferedInputStream(urlConnection.inputStream)

                do {
                    bufferLength = inPut.read(buffer)
                    if (bufferLength > 0) {
                        fileOutput.write(buffer, 0, bufferLength)
                        downloadedSize += bufferLength
                        counter += bufferLength
                    } else {
                        break
                    }
                } while (true)

                urlConnection.disconnect()
                fileOutput.close()

            } catch (e: MalformedURLException) {
            } catch (e: IOException) {
            } finally {
                runOnUiThread {
                    if (file.exists()) {
                        mLoadingView.visibility = View.GONE
                        openFile(file)
                    }
                }
            }
        }).start()
    }

    private fun openFile(file: File) {
        if (file.length() == 0L) {
//            mLoadingView.visibility = View.GONE
            toast("网络异常，请检查网络")
            return
        }
        val bundle = Bundle()
        bundle.putString("filePath", file.absolutePath)
        val tempPath = File(Environment.getExternalStorageDirectory(), "$packageName/TbsReaderTemp")
        if (!tempPath.exists()) {
            tempPath.mkdirs()
        }
        bundle.putString("tempPath", tempPath.absolutePath)
        val suffix = "" + FileTypeJudge.getType(file.absolutePath)?.name?.toLowerCase()
        Log.e("suffix", "$suffix")
        val result = mTbsReaderView!!.preOpen(suffix, false)
        //offlice 文件
        if (result) {
            rl_root.addView(
                mTbsReaderView,
                RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.MATCH_PARENT,
                    RelativeLayout.LayoutParams.MATCH_PARENT
                )
            )
            mTbsReaderView?.openFile(bundle)
//            mLoadingView.visibility = View.GONE
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mTbsReaderView?.onStop()
    }

    override fun onCallBackAction(p0: Int?, p1: Any?, p2: Any?) {
//        Log.e("onCallBackAction", "p0:" + p0 + "\tp1:" + p1?.toString() + "\tp2:" + p2?.toString())
    }

    fun md5(text: String): String {
        try {
            val instance: MessageDigest = MessageDigest.getInstance("MD5")//获取md5加密对象
            val digest: ByteArray = instance.digest(text.toByteArray())//对字符串加密，返回字节数组
            var sb = StringBuffer()
            for (b in digest) {
                var i: Int = b.toInt() and 0xff//获取低八位有效值
                var hexString = Integer.toHexString(i)//将整数转化为16进制
                if (hexString.length < 2) {
                    hexString = "0$hexString" //如果是一位的话，补0
                }
                sb.append(hexString)
            }
            return sb.toString()

        } catch (e: NoSuchAlgorithmException) {
        }
        return ""
    }
}